using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using Object = UnityEngine.Object;

namespace AutoInjector.Editor
{
    public static class Finder
    {
        public static T SearchInProject<T>(string filter = "") where T : Object
        {
            return SearchInProject(typeof(T), filter) as T;
        }
        
        public static Object SearchInProject(Type type, string filter = "")
        {
            string[] guids = AssetDatabase.FindAssets($"t: {type.Name}");
            if (guids == null)
            {
                return null;
            }

            IEnumerable<string> assetPaths = guids.Select(AssetDatabase.GUIDToAssetPath);
            string assetPath = string.IsNullOrEmpty(filter)
                ? assetPaths.FirstOrDefault()
                : assetPaths.FirstOrDefault(x => Regex.IsMatch(x, filter));
            if (string.IsNullOrEmpty(assetPath))
            {
                return null;
            }

            return AssetDatabase.LoadAssetAtPath(assetPath, type);
        }
    }
}